(function() {
  'use strict';

  angular
	.module('votingBackend')

	.factory('settings', function() {
		return { 
			//base url for production
			// baseUrl: 'http://115.29.194.90:1234/'

			//base url for development
			baseUrl: 'http://localhost:1235/' 
		}
	})

	// DATA SERVICES

	.factory('quizDataService', function ($http, $resource, settings) {
	   
		var quizDataService = {}
		var baseUrl = settings.baseUrl;
		var dataService = {}

		quizDataService.getQuizzes = function () {
			return $resource(baseUrl + 'quiz').query();
		};

		quizDataService.getQuizById = function (quiz) {
			return $resource(baseUrl + 'quiz/:id').get(
				{
					id : quiz
				}
			)
		};

		return quizDataService;

	})

	.factory('questionDataService', function ($http, $resource, settings) {

		var questionDataService = {};
		var baseUrl = settings.baseUrl;

		questionDataService.getQuestions = function () {
			return $resource(baseUrl + 'question').query();
		};

		questionDataService.getQuestionById = function (question) {
			return $resource(baseUrl + 'question/:id').get(
				{
					id : question
				}
			)
		}

		//questionDataService.getQuestionsByQuiz = function (quiz) {
		//    return $resource(baseUrl + 'question/:id')
		//}

		return questionDataService;
	})

	.factory('answerDataService', function ($http, $resource, settings) {

	  var answerDataService = {};
	  var baseUrl = settings.baseUrl;

	  answerDataService.getAnswers = function (question) {

	  }

	  return answerDataService;
	})

	.factory('userDataService', function ($resource, $http, settings, quizDataService, questionDataService){
		
		var userDataService = {};
		userDataService.userData = {};
		var baseUrl = settings.baseUrl;

		userDataService.getUsers = function () {
			return $resource(baseUrl + 'user').query();
		};

		userDataService.getUserById = function (user) {
			return $resource(baseUrl + 'user/:id').get(
				{
					id : user
				}
			)
		}

		userDataService.provideAllUserData = function (user) {

			return userDataService.getUserById(user)
			.$promise.then(function (res){
				
				userDataService.userData['name'] = res.name;
				userDataService.userData['id'] = res.id;
				userDataService.userData['quizzes'] = res.quizzes;
				userDataService.userData['email'] = res.email;
				userDataService.userData['profileImage'] = res.profileImage;

				 var updateUserDataWithQuestions = function(i) {
					quizDataService.getQuizById(res.quizzes[i].id)
					.$promise.then(function (res) {
						userDataService.userData.quizzes[i]['questions'] = res.questions;
						
						//get questions in quiz by id and add their answers to the user data object
						var updateQuestionDataWithAnswers = function(j){
							questionDataService.getQuestionById(res.questions[j].id)
							.$promise.then(function (res) {
								userDataService.userData.quizzes[i]['questions'][j]['answers'] = res.answers
							})
						}

						for (var j = 0; j < res.questions.length; j++) {
								updateQuestionDataWithAnswers(j);							
						}
					})
				}
				
				for (var i = 0; i < userDataService.userData.quizzes.length; i++){
					updateUserDataWithQuestions(i);                
				}
				
			})
		}

		userDataService.provideAllUserActivity = function (user) {
			return $http.get(baseUrl + 'vote?userId=' + user)
			.then(function (res){
				userDataService.userData['activity'] = res.data
			}, function (err){
				console.log(err)
			})
		}

		return userDataService;
   
   })

	// AUTHORIZATION SERVICES

	.factory('AuthService', function ($http, Session, settings) {
	  var authService = {};
	  var baseUrl = settings.baseUrl;
	 
	  authService.login = function (credentials) {
		//console.log(credentials)
		return $http
		  // production
		  //.put('http://115.29.194.90:1234/login', credentials)
		  // development
		  .put(baseUrl + 'login', credentials)
		  .then(function (res) {
			// THIS IS MY HACKY WORKAROUND WAY TO CREATE THE SESSION
			Session.create(res.data.id, res.data.id, res.data.id)
			return res.data.id
			// THIS IS THE CORRECT WAY TO CREATE THE SESSION
			//Session.create(res.data.id, res.data.user.id, res.data.user.role);
			//return res.data.user;
		  });
	  };

	  authService.logout = function(){
		return Session.destroy()
	  };
	 
	  authService.isAuthenticated = function () {
		return !!Session.userId;
	  };
	 
	  authService.isAuthorized = function (authorizedRoles) {
		if (!angular.isArray(authorizedRoles)) {
		  authorizedRoles = [authorizedRoles];
		}
		return (authService.isAuthenticated() &&
		  authorizedRoles.indexOf(Session.userRole) !== -1);
	  };
	 
	  return authService;
	})

	//setting everything as the userID for now, come back and add roles / make the session more secure later

	.service('Session', function () {
	  this.create = function (sessionId, userId, userRole) {
		this.id = sessionId;
		this.userId = userId;
		this.userRole = userRole;
	  };
	  this.destroy = function () {
		this.id = null;
		this.userId = null;
		this.userRole = null;
	  };
	})

	
})();
